<?php

namespace app\api\controller;

use think\Db;

// 微信公众号
class Wxgzh
{
    public function responseMsg()
    {
        if (!$this->checkSignature()) {
            return;
        }
        $echoStr = $_GET['echostr'];
        if ($echoStr) {
            echo $echoStr;

            return;
        }
        //get post data, May be due to the different environments
        // $postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $postStr = file_get_contents('php://input');
        if (empty($postStr)) {
            return;
        }

        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $msgType = $postObj->MsgType;
        //处理用户关注信息

        if ('event' == $msgType) {//接收到时间消息
            $event = strtolower($postObj->Event);
            if ('subscribe' == $event) {//关注
                return $this->subscribeEvent($postObj);
            } elseif ('scan' == $event) {//关注后扫描带参数的二维码
                return $this->scanEvent($postObj);
            } elseif ('click' == $event) {//点击自定义查单
                return $this->menuClickEvent($postObj);
            } elseif ('location' == $event) {//地理位置
                return $this->locationEvent($postObj);
            }
        } elseif ('text' == $msgType) {//收到文本消息
            return $this->getTextEvent($postObj);
        } elseif ('image' == $msgType) {//图片消息
        } elseif ('video' == $msgType) {//视频消息
        } elseif ('location' == $msgType) {//位置信息
            return $this->locationEvent1($postObj);
        } elseif ('link' == $msgType) {//链接消息
        }
    }

    private function subscribeEvent($postObj)//关注事件
    {
        $eventKey = strval($postObj->EventKey);
        if (!$eventKey) {//直接关注
            $response = '感谢关注“羽毛球联盟”公众号';
            // 获取用户信息
            $wx_service = new \wx\WxgzhService();
            $user_info = $wx_service->getSubUserInfo($postObj->FromUserName);
            $db_gzh_info = Db::name('gzh_user')->where(['openid' => $user_info['openid']])->find();
            if (!$db_gzh_info) {
                Db::name('gzh_user')->insert($user_info);
            }
            if ($user_info['unionid']) {
                // 解决先关注公众号 再登录小程序 就没有关注包了 （登录小程序 之后取消关注再关注公众号就有了）
                $db_u_info = Db::name('user')->where(['unionid' => $user_info['unionid']])->find();
                if ($db_u_info) {
                    if (!$db_u_info['gzh_openid']) {
                        Db::name('user')->where('id', $db_u_info['id'])->update(['gzh_openid' => $user_info['openid']]);
                        Db::name('admin')->where(['openid' => $db_u_info['openid']])->update(['gzh_openid' => $user_info['openid'], 'unionid' => $user_info['unionid']]);
                    }
                    $red_packet_info = Db::name('red_packet')->where(['user_id' => $db_u_info['id'], 'type' => '关注红包'])->find();
                    if (!$red_packet_info) {
                        $money = 0.2;
                        $red_packet = ['user_id' => $db_u_info['id'], 'ct' => time(), 'from_user_id' => $db_u_info['id'], 'not_open' => 1, 'money' => $money, 'type' => '关注红包'];
                        Db::name('red_packet')->insert($red_packet);
                        // 红包统计
                        $bt = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                        $et = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                        $total_info = Db::name('total_data')->where(['ct' => [['gte', $bt], ['lte', $et]]])->find();
                        if ($total_info) {
                            Db::name('total_data')->where('id', $total_info['id'])->update(['red_packet' => intval($total_info['red_packet']) + 1, 'red_packet_money' => round($total_info['red_packet_money'] + $money, 2)]);
                        } else {
                            Db::name('total_data')->insert(['ct' => time(), 'red_packet' => 1, 'red_packet_money' => $money]);
                        }
                    }
                }
            }

            return $wx_service->postTextEvent($postObj, $response);
        } else {//扫描带参数的二维码
            return $wx_service->scanParaQrEvent($postObj);
        }
    }

    public function checkSignature()
    {
        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];

        $token = config('gzh_token');
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }
}
